package code;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author huang
 * @description
 * @date 2023/4/13 14:25
 * 给你一个字符串数组，请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
 *
 * 字母异位词 是由重新排列源单词的字母得到的一个新单词，所有源单词中的字母通常恰好只用一次。
 *
 * 示例 1:
 * 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
 * 输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
 * 示例 2:
 * 输入: strs = [""]
 * 输出: [[""]]
 * 示例 3:
 * 输入: strs = ["a"]
 * 输出: [["a"]]
 *
 *
 * 提示：
 * 1 <= strs.length <= 104
 * 0 <= strs[i].length <= 100
 * strs[i] 仅包含小写字母
 *
 * 来源：力扣（LeetCode）49题
 * 链接：https://leetcode.cn/problems/group-anagrams
 */
public class Zimu49 {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<String> af = new LinkedList<>();
        List<String> hou = new LinkedList<>();
        List<List<String>> zui = new LinkedList<>();
        for (int i = 0; i < strs.length; i++) {
            af.add(strs[i]);
            String[] strings = strs[i].split("");
            List<String> collect = Arrays.stream(strings).sorted().collect(Collectors.toList());
            hou.add(collect.toString());
        }
        for (int i = 0; i < hou.size(); i++) {
            for (int j = 1;j<hou.size()-1;j++){
                if (i == j){
                    break;
                }
                if (hou.get(i).equals(hou.get(j))){
                    List<String> q = new LinkedList<>();
                    q.add(af.get(i));
                    q.add(af.get(j));
                    zui.add(q);
                }
            }
        }
        return zui;
    }

    public static void main(String[] args) {


        String[] tool = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        Zimu49 zimu49 = new Zimu49();
        List<List<String>> list = zimu49.groupAnagrams1(tool);


        System.out.println(list);

    }

    public List<List<String>> groupAnagrams1(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }




}
